package com.jeequan.jeepay.pay.channel.pmipay.payway;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.model.params.pmipay.PmipayNormalMchParams;
import com.jeequan.jeepay.pay.channel.pmipay.PmipayPaymentService;
import com.jeequan.jeepay.pay.model.MchAppConfigContext;
import com.jeequan.jeepay.pay.rqrs.AbstractRS;
import com.jeequan.jeepay.pay.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.pay.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.pay.rqrs.payorder.UnifiedOrderRS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.SocketTimeoutException;

/**
 * Paymob Api放款
 */
@Slf4j
@Service
public class PaymobPayinRn extends PmipayPaymentService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PaymobPayinTokenService paymobPayinTokenService;


    private static String NA = "NA";

    @Override
    public String preCheck(UnifiedOrderRQ bizRQ, PayOrder payOrder) {
        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ bizRQ, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {

        UnifiedOrderRS orderRS = new UnifiedOrderRS();
        orderRS.setMchOrderNo(payOrder.getMchOrderNo());
        orderRS.setPayOrderId(orderRS.getPayOrderId());
        orderRS.setMchOrderNo(orderRS.getMchOrderNo());
        orderRS.setOrderState(PayOrder.STATE_INIT);

        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        orderRS.setChannelRetMsg(channelRetMsg);

        PmipayNormalMchParams config = (PmipayNormalMchParams) mchAppConfigContext.getNormalMchParamsByIfCode(CS.IF_CODE.PMIPAY);
        String accessToken = paymobPayinTokenService.getToken(config);
        StringBuilder sb = new StringBuilder(config.getDomain());
        sb.append("/api/ecommerce/orders");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);

        PayinRnRequestParams params = PayinRnRequestParams.builder()
                .auth_token(accessToken)
                .amount_cents(bizRQ.getAmount().longValue())
                .currency(bizRQ.getCurrency())
                .delivery_needed("false")
                .merchant_order_id(bizRQ.getMchOrderNo())
                .build();

        String body = JSONObject.toJSONString(params);
        HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);

        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(sb.toString(), HttpMethod.POST, httpEntity, String.class);
            log.info("响应状态：{}，响应结果：{}", responseEntity.getStatusCodeValue(), responseEntity.getBody());
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                JSONObject result = JSONObject.parseObject(responseEntity.getBody());
                long orderId = result.getLong("id");
                channelRetMsg.setChannelOrderId(String.valueOf(orderId));
                if (orderId > 0) {
                    // 订单创建成功
                    payOrder.setChannelOrderNo(channelRetMsg.getChannelOrderId());
                    String paymentKey = getPaymentKey(bizRQ, payOrder, config, accessToken);
                    // TODO 生成还款码

                }
            }
        } catch (Exception ex) {
            if (ex.getClass().isInstance(SocketTimeoutException.class)) {
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.UNKNOWN);
            } else {
                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            }
            log.error("创建代付订单异常", ex);
        }

        return orderRS;
    }


    private String getPaymentKey(UnifiedOrderRQ bizRQ, PayOrder payOrder, PmipayNormalMchParams config, String accessToken) {
        StringBuilder sb = new StringBuilder(config.getDomain());
        sb.append("/api/acceptance/payment_keys");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);

        JSONObject billData = new JSONObject();
        billData.put("apartment", "");
        billData.put("email", "");
        billData.put("floor", "");
        billData.put("first_name", "");
        billData.put("street", "");
        billData.put("building", "");
        billData.put("phone_number", "");
        billData.put("shipping_method", "");
        billData.put("postal_code", "");
        billData.put("city", "");
        billData.put("country", "");
        billData.put("last_name", "");
        billData.put("state", "");

        JSONObject params = new JSONObject();
        params.put("auth_token", accessToken);
        params.put("amount_cents", payOrder.getAmount().longValue());
        params.put("expiration", 1800);
        params.put("order_id", payOrder.getChannelOrderNo());
        params.put("billing_data", billData);
        params.put("currency", "EGP");
        params.put("integration_id", config.getKioskId());
        params.put("lock_order_when_paid", "false");


        String body = JSONObject.toJSONString(params);
        HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);

        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(sb.toString(), HttpMethod.POST, httpEntity, String.class);
            log.info("响应状态：{}，响应结果：{}", responseEntity.getStatusCodeValue(), responseEntity.getBody());
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                JSONObject result = JSONObject.parseObject(responseEntity.getBody());
                return result.getString("token");
            }
        } catch (Exception ex) {
            log.error("创建订单-获了payment-key异常", ex);
        }
        return null;
    }

}
